#include "TUIBase.h"
#include "TUIList.h"
#include "TUIInfo.h"
#include <malloc.h>
#include <pthread.h>


const char* strError[ERROR_NUM] = {
  " ",
  "passwords not same!",
  "CH1 waiting ready..",
  "CH2 waiting ready..",
  "CH3 waiting ready.."
};

typedef struct mTUI_ListItem {  
  stList_Head stListHead;
  int InfoID;
  char InfoType;
}TUI_ListItem;  

stList_Head         stListHead;  
stList_Head         *pstListHead= NULL;  
//pthread_mutexattr_t m_listMux;

void TUI_infoInit()
{
  pstListHead = &stListHead;  
  list_init(pstListHead);
  TUI_dispInfo(TUI_TEXT_ERROR,strError[ERROR_NONE],strlen(strError[ERROR_NONE])+1);
  //pthread_mutexattr_init(&m_listMux);
}
void TUI_addInfo(int InfoID, char InfoType)
{
  stList_Head* pHead;
  TUI_ListItem* item;
  if(pstListHead == NULL)
    return;
  list_for_each_item_rev(pHead, pstListHead)
  {
    item = list_entry(pHead,TUI_ListItem,stListHead);
    if(item->InfoID == InfoID)
    {
      return;
    }
  }

  item =(TUI_ListItem *)malloc(sizeof(TUI_ListItem));
  if (NULL == item)  
  {  
    printf("TUIInfo malloc fail!");  
    return;  
  }  

  item->InfoID = InfoID;
  item->InfoType = InfoType;
  //pthread_mutex_lock(&m_listMux);
  list_add(&(item->stListHead), pstListHead);
  TUI_dispInfo(TUI_TEXT_ERROR,strError[item->InfoID],strlen(strError[item->InfoID])+1);
  //pthread_mutex_unlock(&m_listMux);
}
void TUI_deleteInfo(int InfoID)
{
  stList_Head* pHead;
  TUI_ListItem* item;
  if(pstListHead == NULL)
    return;
  list_for_each_item_rev(pHead, pstListHead)
  {
    item = list_entry(pHead,TUI_ListItem,stListHead);
    if(item->InfoID == InfoID)
    {
      list_remove(pHead);   //remove item from list
      free(item);
      break;
    }
  }
}
void TUI_updateInfo()
{
  if(pstListHead == NULL)
    return;
  if(list_is_empty(pstListHead))
  {
    TUI_dispInfo(TUI_TEXT_ERROR,strError[ERROR_NONE],strlen(strError[ERROR_NONE])+1);
    return;
  }
  stList_Head* pHead;
  TUI_ListItem* item;
  pHead = list_prev_item(pstListHead);//get the end of list
  item = list_entry(pHead,TUI_ListItem,stListHead);//get the info item from head
  list_remove(&(item->stListHead));   //remove item from list

  TUI_dispInfo(TUI_TEXT_ERROR,strError[item->InfoID],strlen(strError[item->InfoID])+1);

  if(item->InfoType == ERROR_ONCE)
    free(item);
  else if(item->InfoType == ERROR_ALWAYS)
    list_add(&(item->stListHead), pstListHead);

}
